<template>
<div style="width: 100%;height: 100vh; background-color: darkcyan; overflow: hidden">
  <div style="width: 400px;margin: 150px auto">
    <div style="color: aliceblue ; font-size: 30px; text-align: center; padding: 30px">新用户注册</div>

    <el-form :model="form" ref="form" size="normal" :rules="rules">
      <el-form-item  prop="username">
        <el-input :prefix-icon="Avatar" v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item  prop="password">
        <el-input :prefix-icon="Lock" v-model="form.password" show-password></el-input>
      </el-form-item>
      <el-form-item  prop="confirm">
        <el-input :prefix-icon="Lock" v-model="form.confirm" show-password></el-input>
      </el-form-item>
      <el-form-item  prop="name">
        <el-button style="width: 100%;" type="primary" @click="register">立即注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</div>
</template>

<script>
//导入需要使用的图标(注意导入图标库时需要在管理员运行的模式下)
import { Avatar, Lock } from "@element-plus/icons-vue";
import request from "../../utils/request";
import router from "@/router";



export default {
  //再setup一下，之后就可以在页面中使用了
  setup() {
    return {
      Avatar,
      Lock
    }
  },

  name: "Register",
  //定义数据
  data() {
    return {
      form: {},
      //指定规则，如果没有输入数据则会提示
      rules: {
        username: [
          {required: true, message: "请输入用户名",trigger: 'blur'}
        ],
        password: [
          {required: true, message: "请输入密码",trigger: 'blur'}
        ],
        confirm: [
          {required: true, message: "请确认密码",trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    //注册方法
    register() {

      //判断两次输入的密码是否一致（用户名是否重复）
      if (this.form.password != this.form.confirm){
        this.$message({
          type: "error",
          message: "两次密码输入不一致"
        })
        return  //终止执行
      }

      //当rules满足，才能发送请求
      this.$refs["form"].validate((valid) => {
        if (valid) {

          //将表单中的数据通过request.post传输给后台，后台通过res返回数据
          request.post("/user/register",this.form).then(res => {
            if (res.code === '0'){
              this.$message({
                type: "success",
                message: "注册登陆成功"
              })
              //页面跳转
              router.push("/login")  //注册成功之后需要跳转回登录界面
            }else {
              this.$message({
                type: "error",
                message: res.msg
              })
            }
          })

        }
      })


    }
  }
}
</script>

<style scoped>

</style>